package cn.imnaer.service.rpc.recommend.dao;

import cn.imnaer.common.factory.JacksonUtil;
import cn.imnaer.database.BaseDao;
import cn.imnaer.database.DBAccessAPIHelp;
import cn.imnaer.database.MatchConst;
import cn.imnaer.database.define.DBConstant;
import cn.imnaer.service.persistence.model.State;
import cn.imnaer.service.persistence.model.consts.STATE;
import cn.imnaer.service.rest.view.model.Place;

import org.bson.BSONObject;
import org.bson.BasicBSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StateDaoImpl extends BaseDao<State> {
	private static StateDaoImpl stateActiveRecord = new StateDaoImpl();

	public static StateDaoImpl getInstance() {

		return stateActiveRecord;

	}

	private StateDaoImpl() {
		this.dbSpaceName = DBConstant.SPACE.PLACE_INFO_SPACE;
		this.dbCollectionName = DBConstant.COLLECTION.STATE_INFO_COLLECTION;
	}

	public State putStateList(String json) {
		DBAccessAPIHelp apiHelp = new DBAccessAPIHelp();
		State obj = (State) JacksonUtil.jsonToBean(json, State.class);
		// apiHelp.insertJsonObject(spaceStr, collectionStr, obj);
		return obj;

	}

    public State findByStateCode(String stateCode) {
        BSONObject query = new BasicBSONObject();
        query.put(STATE.stateCode, stateCode);
        State target = this.findOne(query);
        return target;
    }

	public List<Place> search(String keywords) {
		List<Place> placeList = new ArrayList<Place>();
		if (keywords != null && !keywords.isEmpty()) {
			BSONObject mather = new BasicBSONObject();
			Pattern pattern = Pattern.compile("[a-zA-Z]*");
			Matcher matcher = pattern.matcher(keywords);
			BSONObject query = new BasicBSONObject();
			if (matcher.matches()) {
				mather.put(MatchConst._REGEX, keywords);
				query.put(STATE.pinyin, mather);
			} else {
				mather.put(MatchConst._REGEX, keywords);
				query.put(STATE.stateName, mather);
			}
			List<State> list = this.findAll(query, null);

			for (State state : list) {
				Place place = new Place();
				place.setAttribute(state);
				placeList.add(place);
			}

		}
		return placeList;

	}

	@Override
	protected String getDbSpaceName() {
		// TODO Auto-generated method stub
		return DBConstant.SPACE.PLACE_INFO_SPACE;
	}

	@Override
	protected String getDbCollectionName() {
		// TODO Auto-generated method stub
        return DBConstant.COLLECTION.STATE_INFO_COLLECTION;
	}

	@Override
	protected String getPrimaryKey() {
		// TODO Auto-generated method stub
		return null;
	}

}
